package com.jmu.bishe.web.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.jmu.bishe.entity.Member;
import com.jmu.bishe.entity.News;
import com.jmu.bishe.service.NewsService;
import com.jmu.bishe.service.main.TableService;
import com.jmu.bishe.utils.BeanUtils;
import com.jmu.bishe.utils.StringUtils;
import com.jmu.bishe.utils.UUIDGenerator;
import com.jmu.bishe.web.common.BaseController;

@Controller
public class NewsController extends BaseController{

	@Autowired
	private TableService tableService;
	
	@Autowired
	private NewsService newsService;

	/**
	 * 用户发布新闻
	 * @param model
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/admin/publish-news.do") 
    public String publishnews(Model model,HttpServletRequest request) throws Exception {
		if(!StringUtils.isBlank(request.getParameter("nid"))){
			News news = newsService.getNews(request.getParameter("nid"));	
			Member m = getCurUser(request);
			if(!news.getUserId().equals(m.getUserId())&&!"0".equals(m.getRole())){
				//是本人发布的或者是超级管理员，才可以修改
				return "redirect:/admin/my-news.do";
			}
			model.addAttribute("news", news);
		}
        return "publish-news";
    }
	
	/**
	 * 用户发布新闻处理
	 * @param model
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/admin/publish-news.do",method=RequestMethod.POST) 
    public String dopublishnews(Model model,HttpServletRequest request,News news) throws Exception {
		Member m = getCurUser(request);
		if(StringUtils.isBlank(news.getNid())){
			//NID为空，是新增			
			news.setNid(UUIDGenerator.generate());			
			news.setUserId(m.getUserId());
			news.setRecordDate(new Date());
			news.setStatus(0);			
			newsService.saveOrUpdate(news);
		}else{
			News oldNews =  newsService.getNews(news.getNid());
			if(oldNews.getUserId().equals(m.getUserId())||"0".equals(m.getRole())){
				//是本人发布的或者是超级管理员，才可以修改
				BeanUtils.BeanToBean(news, oldNews);
				newsService.saveOrUpdate(oldNews);
			}
		}
		
		return "redirect:/admin/my-news.do";
    }
	/**
	 * 新闻内容
	 * @param model
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/news/newscontent.do") 
    public String donewscontent(Model model,HttpServletRequest request) throws Exception {	
		String nid = request.getParameter("nid");
		News news = newsService.getNews(nid);
		Member m = getCurUser(request);
		if(!"1".equals(news.getStatus())){
			//没有通过审核的，判断是否是自己发布的或者是超级管理员，否则报找不到。
			if(m==null||(!news.getUserId().equals(m.getUserId())&&!"0".equals(m.getRole()))){
				return "errors/404";
			}		
		}	
		model.addAttribute("news",news);
		return "newscontent";
    }
	/**
	 * 新闻列表
	 * @param model
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/news/newslist.do") 
    public String newlist(Model model,HttpServletRequest request) throws Exception {	
        //取得查询条件
        Map paramMap = newsService.getParamMap(request);
        List params = (List)paramMap.get("tjs");
        String sql = (String)paramMap.get("sql");
     
        //取得参数
        String _currentPage = request.getParameter("currentPage");
        String _linePerPage = request.getParameter("linePerPage");
        int currentPage = _currentPage == null ? 1 : StringUtils.getStringToInt(_currentPage);
        int linePerPage = _linePerPage == null ? 10 : StringUtils.getStringToInt(_linePerPage);
        //获取查询列表
        List list = tableService.queryForList(sql, params,currentPage,linePerPage);
        _convertVisitorList(list);
        model.addAttribute("list",list);
        //获取总页数
        int totalNumber = tableService.getTotalNumber(sql,params);
        //放参数
        int totalPage = totalNumber/linePerPage;
        model.addAttribute("totalPage",totalPage+1);
        model.addAttribute("linePerPage",linePerPage);
        model.addAttribute("currentPage",currentPage);
        Map requestParamMap = request.getParameterMap();
        Iterator iterator = requestParamMap.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry entry = (Map.Entry) iterator.next();
            String key = StringUtils.getObjectToString(entry.getKey());
            String value = request.getParameter(key);
            if("keywords".equals(key)){
            	//这边注意，页面url get传参对中文 使用了encodeURI(encodeURI(keywords));所以我们要还原
            	try {
            		value = URLDecoder.decode(value,"utf-8");
        		} catch (UnsupportedEncodingException e) {
        			logger.info("中文参数编码失败！",e);
        		}
            }else if("dateType".equals(key)){
//            	<a class="fcbl " dataType="1" data='2013-06-02' href="#">今日</a>
//    			<a class="fcbl " dataType="2" data='2013-06-02' href="#">本周</a>
//    			<a class="fcbl " dataType="3" data='2013-06-01' href="#">本月</a>
//    			<a class="fcbl " dataType="4" data='2013-01-01' href="#">本年</a>
            	if("1".equals(value)){
            		model.addAttribute("dateTypeZW", "今日");
            	}else if("2".equals(value)){
            		model.addAttribute("dateTypeZW", "本周");
            	}else if("3".equals(value)){
            		model.addAttribute("dateTypeZW", "本月");
            	}else if("4".equals(value)){
            		model.addAttribute("dateTypeZW", "本年");
            	}
            }
            model.addAttribute(key,value);
        }
        
        return "newslist";
    }
	private void _convertVisitorList(List list){
		if(list!=null){
			for(Object obj:list){
				Map map = (Map)obj;
				String content = StringUtils.getObjectToString(map.get("CONTENT"));
				if(content.length()>200){
					map.put("DISPLAY_CONTENT", content.substring(0, 200));
				}else{
					map.put("DISPLAY_CONTENT", content);
				}
			}
		}
	}
}
